package org.epay.service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.epay.action.PCErrorPack;
import org.epay.action.TokenAction;
import org.epay.config.CommonConfig;
import org.epay.http.HOpCode;
import org.epay.model.base.Token;
import org.epay.protobuf.http.PCErrorProto.PCError;
import org.epay.protobuf.http.PCErrorProto.PCErrorCode;
import org.epay.protobuf.http.TokenProto.GetTokenC;
import org.epay.protobuf.http.TokenProto.GetTokenS;
import org.epay.tool.TimeUtils;
import org.grain.httpserver.HttpException;
import org.grain.httpserver.HttpPacket;
import org.grain.httpserver.IHttpListener;

public class TokenService implements IHttpListener {
	@Override
	public Map<String, String> getHttps() {
		HashMap<String, String> map = new HashMap<>();
		map.put(HOpCode.GET_ADMIN_TOKEN, "getAdminTokenHandle");
		return map;
	}

	public HttpPacket getAdminTokenHandle(HttpPacket httpPacket) throws HttpException {
		GetTokenC message = (GetTokenC) httpPacket.getData();
		if (!CommonConfig.ADMIN_NAME.equals(message.getUserName())) {
			PCError errorPack = PCErrorPack.create(PCErrorCode.ERROR_CODE_8, httpPacket.hSession.headParam.hOpCode);
			throw new HttpException(HOpCode.PC_ERROR, errorPack);
		}
		// 判断密码
		if (!CommonConfig.ADMIN_PASSWORD.equals(message.getUserPassword())) {
			PCError errorPack = PCErrorPack.create(PCErrorCode.ERROR_CODE_8, httpPacket.hSession.headParam.hOpCode);
			throw new HttpException(HOpCode.PC_ERROR, errorPack);
		}
		Token token = TokenAction.getTokenByUserId(CommonConfig.ADMIN_NAME);
		if (token == null) {
			token = TokenAction.createToken(CommonConfig.ADMIN_NAME);
			if (token == null) {
				token = TokenAction.getTokenByUserId(CommonConfig.ADMIN_NAME);
			}
		} else {
			Date date = new Date();
			// 判断是否过期
			if (date.getTime() > token.getTokenExpireTime().getTime()) {
				TokenAction.deleteToken(token.getTokenId());
				token = TokenAction.createToken(CommonConfig.ADMIN_NAME);
				if (token == null) {
					token = TokenAction.getTokenByUserId(CommonConfig.ADMIN_NAME);
				}
			} else {
				TokenAction.updateToken(token.getTokenId());
			}
		}
		if (token == null) {
			PCError errorPack = PCErrorPack.create(PCErrorCode.ERROR_CODE_8, httpPacket.hSession.headParam.hOpCode);
			throw new HttpException(HOpCode.PC_ERROR, errorPack);
		}
		GetTokenS.Builder builder = GetTokenS.newBuilder();
		builder.setHOpCode(httpPacket.hSession.headParam.hOpCode);
		builder.setTokenId(token.getTokenId());
		builder.setTokenExpireTime(TimeUtils.dateToString(token.getTokenExpireTime()));
		HttpPacket packet = new HttpPacket(httpPacket.hSession.headParam.hOpCode, builder.build());
		return packet;
	}
}
